<?php

namespace addons\booking\model;

use think\Model;


class Lodgers extends Model
{

    // 表名
    protected $name = 'booking_lodgers';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text'
    ];

    protected static function init()
    {
        self::beforeInsert(function ($row) {
            $data = self::where('type', $row)->where('idnumber')->find();
            if ($data) {
                throw new \Exception("{$row['name']}已存在，无需重复添加");
            }
        });
    }

    public function getTypeList()
    {
        return ['0' => __('Type 0'), '1' => __('Type 1'), '2' => __('Type 2'), '3' => __('Type 3')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 住客列表
     *
     * @param array $param
     * @return \think\Paginator
     */
    public static function tableList($param)
    {
        $pageNum = 15;
        if (isset($param['num']) && !empty($param['num'])) {
            $pageNum = $param['num'];
        }

        return self::field('id,user_id,name,type,idnumber,createtime')->where(function ($query) use ($param) {

            if (isset($param['user_id']) && !empty($param['user_id'])) {
                $query->where('user_id', $param['user_id']);
            }

        })->order('createtime desc')->paginate($pageNum);
    }


}
